<?php
require_once('classes/config.inc.php');
require_once(DIR_CLASS. 'Session.php');
require_once(DIR_CLASS. 'Database.php');
include(DIR_CLASS. 'TemplateParser.php');
include(DIR_CLASS. 'Form.php');

$session = new UserSession();
$session->open();
if($session->check())
	$menu = "<a href=\"profile.php\">Profil</a> / <a href=\"login.php?act=logout\">Logga ut</a>[". substr($session->getEmail(),0,12) ."] / <a href=\"\">Karta &ouml;ver hemsidan</a>";
else
	$menu = "<a href=\"register.php\">Registrera dig</a> / <a href=\"login.php\">Logga in</a> / <a href=\"sitemap.php\">Karta &ouml;ver hemsidan</a>";
	
if ($session->check()){
	if(isset($_GET['act']) && $_GET['act'] == "logout"){
		$session->destroy();
	}
	header('Location: index.php');
	die();
}

if(isset($_POST['action']) && $_POST['action'] == "login"){
	$form = new Form();
	$formElements = array("email" => 1,"pass" => 1);
	$form->open($formElements);
	
	if($form->isValidForm()){
		$db = new MYSQLDatabase(DB_SERVER,DB_USER,DB_PASS,DB_DATABASE);
		$login_sql = "SELECT * FROM ". TABLE_USERS ." WHERE(email='".$form->get("email")."' AND pass='".md5($form->get("pass"))."') LIMIT 0,1";
		try {
			$db->connect();
			$link = $db->query($login_sql);
			if(mysql_num_rows($link)>0){
				$res = mysql_fetch_array($link);
				$session->save($res["id"],$res["email"],$res["level"]);
				$sql = "UPDATE ".TABLE_USERS. " SET last_online=NOW() WHERE(id=".$res["id"].") LIMIT 0,1";
				$link = $db->query($sql);
				
				header('Location: index.php');
				die();
			}
			else{
				$error='Error: Invalid username or password';
			}
		}catch (Exception $e){
			$error='Error: ' . $e->getMessage();
		}
	}
	else
	{
	 $error='Error: Invalid username or password';
	}
	$template_array = array("ERROR"=> $error);
		
	$template = new TemplateParser();
	$template->loadfile("templates/login.tpl");
	$template->assignVars($template_array);
	$template->output();
}
else {
	$template_array = array("MENU" => $menu, "ERROR"=> "");
	
	$template = new TemplateParser();
	$template->loadfile("templates/login.tpl");
	$template->assignVars($template_array);
	$template->output();
}
?>